package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import beans.CartBean;
import beans.ErrorBean;
import beans.OrderBean;
import beans.OrderList;
import beans.UserBean;

public class CheckoutDispatcher extends HttpServlet {

	private static String cart_page = null;
	private static String error_page = null;
	private static String shop_page = null;
	private static String login_page = null;
	private static String order_page = null;
	private static String myorder_page = null;
	
	private static final String ERROR = "errorMessage";
	private static final String USER_PROFILE = "user_profile";
	
	/**
	 * Constructor of the object.
	 */
	public CheckoutDispatcher() {
		super();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
		cart_page = this.getInitParameter("PAGE_CART");
		error_page = this.getInitParameter("PAGE_ERROR");
		shop_page = this.getInitParameter("PAGE_SHOP");
		login_page = this.getInitParameter("PAGE_LOGIN");
		order_page = this.getInitParameter("PAGE_NEWORDER");
		myorder_page = this.getInitParameter("PAGE_MYORDERS");
		
	}


	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * The processRequest method of the servlet. <br>
	 * 
	 * This method is called when a request is received
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	@SuppressWarnings("unchecked")
	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		String action = request.getParameter("action");
		
		if(action.equals("cart")){
			request.getRequestDispatcher(cart_page).forward(request, response);
		} else if(action.equals("checkout")){
			HttpSession session = request.getSession();
			if(session.getAttribute(USER_PROFILE) == null){
				request.getRequestDispatcher(login_page).forward(request, response);
			} else {
				CartBean cart = (CartBean)session.getAttribute("CART");
				if(cart == null || cart.getItems().size() == 0){
					gotoErrorPage(request, response, "You should buy something firstly.");
					return;
				}
				OrderBean order = new OrderBean();
				if(order.isValid(cart)){
					request.getRequestDispatcher(order_page).forward(request, response);
				} else {
					gotoErrorPage(request, response, "We have not enough components to creat your order currently!");
					return;
				}

			}
		} else if(action.equals("update")){
			//update the CART attribute in session and the cart page
			Map<String, String[]> cartMap = (Map<String, String[]>)request.getParameterMap();
			Set<Map.Entry<String, String[]>> cartItems = cartMap.entrySet();
			Iterator<Map.Entry<String, String[]>> iterator = cartItems.iterator();
			while(iterator.hasNext()){
				Map.Entry<String, String[]> entry = iterator.next();
				String parameterName = entry.getKey();
				String parameterValue = entry.getValue()[0];
				
				if(parameterName.indexOf("item_", 0) != -1){
					try{
						int productID = Integer.parseInt(parameterName.split("_")[1]);
						int productNumber = Integer.parseInt(parameterValue);
						HttpSession session =  request.getSession();
						if(session.getAttribute("CART") != null){
							CartBean cartBean = (CartBean)session.getAttribute("CART");
							cartBean.remove(productID, productNumber);
							session.setAttribute("CART", cartBean);
						}
					} catch (Exception e){
						
					}

				}
			}
			
			request.getRequestDispatcher(cart_page).forward(request, response);
		} else if(action.equals("order")){
			String recipient = request.getParameter("recipient");
			String address = request.getParameter("address");
			String phone = request.getParameter("phone");
			
			if(recipient == null || address == null || phone == null || recipient.equals("") || address.equals("") || phone.equals("")){
				ErrorBean error = new ErrorBean();
				error.setMessage("All three fields are required");
				request.setAttribute("ERROR", error);
				request.getRequestDispatcher(order_page).forward(request, response);
			} else {
				HttpSession session = request.getSession();
				UserBean user = (UserBean)session.getAttribute(USER_PROFILE);
				if(user == null){
					request.getRequestDispatcher(login_page).forward(request, response);
					return;
				}
				CartBean cart = (CartBean)session.getAttribute("CART");
				if(cart == null || cart.getItems().size() == 0){
					gotoErrorPage(request, response, "You should buy something firstly.");
					return;
				}
				OrderBean order = new OrderBean();
				if(order.newOrder(recipient, address, phone, cart, user)){
					//delete the component from the database
					order.delete(cart);
					//add one new order into database				
					OrderList orders = new OrderList();
					orders.setOrdersByUserID(user.getId());
					request.setAttribute("MYORDERS", orders);
					request.getRequestDispatcher(myorder_page).forward(request, response);
				} else {
					gotoErrorPage(request, response, "Error occurs in the process of ordering");
				}
			}			
		}
	}
	
	private void gotoErrorPage(HttpServletRequest request,
			HttpServletResponse response, String errorMessage)
			throws ServletException, IOException {
		ErrorBean error = new ErrorBean();
		error.setMessage(errorMessage);
		request.setAttribute(ERROR, error);
		request.getRequestDispatcher(error_page).forward(request, response);
	}

}
